package com.mengbuyun.uniplugin;

import static android.content.Context.MEDIA_PROJECTION_SERVICE;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;

import java.util.Date;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 插件入口类
 * 一个页面初始化一次, 初始化完毕之后才能获取到上下文
 */
public class RecordModule extends UniModule {
    private static final int CODE_REQUEST_RECORD = 1;
    private static final int CODE_PERMISSION_RECORD = 2;
    private MediaProjectionManager mMediaProjectionManager;
    private UniJSCallback startRecordCallback;

    private String RECORD_PATH;
    private String File_NAME = String.valueOf(System.currentTimeMillis());
    private Date START_TIME;
    private Date END_TIME;



    private boolean IS_ALLOW_RECORD = true;
    private boolean IS_RECORDING = false;



    private JSONObject optionRecord;



    /**
     * 获取上下文
     */
    public Context getContext(){
        return mUniSDKInstance.getContext();
    }

    public Activity getActivity(){
        return (Activity) getContext();
    }

    /**
     * 开始录屏 - 异步回调结果 uiThread = true
     */
    @UniJSMethod(uiThread = true)
    public void startRecord(JSONObject options, UniJSCallback callback) {
        startRecordCallback = callback;
        if(!IS_ALLOW_RECORD){
            startRecordCallback(504, "当前窗口禁止录屏");
            return;
        }
        if(IS_RECORDING){
            startRecordCallback(505, "已在录屏中");
            return;
        }
        optionRecord = options;
        // 检查录屏权限
        if(!checkRecordPermission()) return;

        // 申请录屏服务
        requestRecord();
    }

    /**
     * 开始录屏的回调
     */
    private void startRecordCallback(int code, String msg) {
        if(startRecordCallback != null) {
            JSONObject data = new JSONObject();
            data.put("code", code);
            data.put("msg", msg);
            startRecordCallback.invoke(data);
            startRecordCallback = null;
        }
    }

    /**
     * 申请录屏服务
     */
    private void requestRecord(){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            startRecordCallback(501, "您的系统不支持录屏功能");
            return;
        }
        if(mMediaProjectionManager == null) mMediaProjectionManager = (MediaProjectionManager) getActivity().getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        getActivity().startActivityForResult(captureIntent, CODE_REQUEST_RECORD);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_RECORD && resultCode == Activity.RESULT_OK) {

//            录屏启动成功
            Cache.ON_START();
            START_TIME = Cache.START_TIME;

            // 允许录屏之后,开启录屏Service
            Intent recordService = new Intent(getActivity(), RecordService.class);
            recordService.putExtra("resultCode", resultCode);
            recordService.putExtra("data", data);

            recordService.putExtra("START_TIME", Cache.START_TIME);


            recordService.putExtra("RECORD_PATH", RECORD_PATH);


            if(optionRecord != null){
                recordService.putExtra("ratio", optionRecord.getIntValue("ratio"));
                recordService.putExtra("frame", optionRecord.getIntValue("frame"));
                recordService.putExtra("isAudio", optionRecord.getBooleanValue("isAudio"));

                String timePattern = optionRecord.getString("timePattern");
                if(timePattern != null){
//                    设置
                    Cache.TIME_PATTERN_DEFAULT = timePattern;
                }

                // 自定义文件名
                String fileName = optionRecord.getString("fileName");
                if(fileName != null  && !File_NAME.isEmpty() && !File_NAME.trim().isEmpty()){
                    //  设置开始时间
                    Params startTimeParams = new Params("time","START_TIME", Cache.START_TIME, Cache.TIME_PATTERN_DEFAULT);
                    File_NAME = ScreenUtils.getFileNameByTemplate(fileName, startTimeParams);
                }
            }

            RECORD_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/" + File_NAME + ".mp4";

            recordService.putExtra("recordPath", RECORD_PATH);




            getActivity().startService(recordService);
            // 成功回调
            startRecordCallback(0, "开始录屏");



            IS_RECORDING = true;
        } else {
            // 失败回调
            startRecordCallback(503, "您已拒绝录屏操作");
        }
    }

    /**
     * 检查录屏权限
     */
    private boolean checkRecordPermission() {
        Activity activity = getActivity();
        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission =
                    ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_PERMISSION_RECORD);
                return false;
            }
        }
        return true;
    }

    /**
     * 权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == CODE_PERMISSION_RECORD){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // 同意授权, 继续录屏
                requestRecord();
            }else{
                // 拒绝授权
                startRecordCallback(502, "您已拒绝录屏权限");
            }
        }
    }

    /**
     * 结束录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public JSONObject stopRecord() {
        JSONObject data = new JSONObject();
        if(IS_RECORDING){
            IS_RECORDING = false;
            Intent service = new Intent(getActivity(), RecordService.class);

            // 设置结束时间
            Cache.ON_END();
            END_TIME = Cache.END_TIME;
            Params endTimeParams = new Params("time","END_TIME", Cache.END_TIME,Cache.TIME_PATTERN_DEFAULT);
            RECORD_PATH = ScreenUtils.getFileNameByTemplate(RECORD_PATH, endTimeParams);
            File_NAME = ScreenUtils.getFileNameByTemplate(File_NAME, endTimeParams);
//            结束
            getActivity().stopService(service);
            data.put("code", 0);
            data.put("msg", "录制成功");
            data.put("RECORD_PATH", RECORD_PATH);
            data.put("FILE_NAME", File_NAME);
            data.put("START_TIME", START_TIME);
            data.put("END_TIME", END_TIME);
            data.put("IS_RECORDING", IS_RECORDING);
        }else{
            data.put("code", 501);
            data.put("msg", "您还未开始录屏");
        }
        return data;
    }

    /**
     * 结束录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public JSONObject getRecordInfo(){
        //   返回：文件名，存储路径，开始时间，结束时间，录制状态
        JSONObject data = new JSONObject();
        data.put("FILE_NAME", File_NAME);
        data.put("RECORD_PATH", RECORD_PATH);
        data.put("START_TIME", START_TIME);
        data.put("END_TIME", END_TIME);
        data.put("IS_RECORDING", IS_RECORDING);
        return data;
    }

    /**
     * 禁止录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public void noRecord() {
        IS_ALLOW_RECORD = false;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    /**
     * 允许录屏 - 同步回调结果 uiThread = false
     */
    @UniJSMethod (uiThread = false)
    public void allowRecord() {
        IS_ALLOW_RECORD = true;
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }
}
